import random
import time
import KBEngine
import KBEDebug as log
import json
import Utils

from base.components import AvatarFarm
from interfaces.ILobbySeasonRank import ILobbySeasonRank
from interfaces.ILobbyGroup import ILobbyGroup
from interfaces.ILoginInfo import ILoginInfo
from interfaces.ILoginPlatform import ILoginPlatform
from interfaces.ILobbyPayment import ILobbyPayment
from interfaces.ILobbyTaskInfo import ILobbyTaskInfo
from interfaces.IAdsInfo import IAdsInfo
from interfaces.ILobbyInviteInfo import ILobbyInviteInfo

# 每小时刷新
TIMER_TYPE_REFRESH_DAILY_TASK = 111
# 每分钟刷新
TIMER_TYPE_REFRESH_MINUTES = 222


class Lobby(KBEngine.Entity,
            ILobbySeasonRank,
            ILobbyGroup,
            ILoginInfo,
            ILoginPlatform,
            ILobbyPayment,
            ILobbyTaskInfo,
            IAdsInfo,
            ILobbyInviteInfo):
    def __init__(self):
        KBEngine.Entity.__init__(self)
        ILobbySeasonRank.__init__(self)
        ILobbyGroup.__init__(self)
        ILoginInfo.__init__(self)
        ILoginPlatform.__init__(self)
        ILobbyPayment.__init__(self)
        ILobbyTaskInfo.__init__(self)
        IAdsInfo.__init__(self)
        ILobbyInviteInfo.__init__(self)
        self.dbVersion = 1
        self.online_avatars = {}
        KBEngine.baseAppData['Lobby'] = self
        self.initRefreshTimer()

    def onDestroy(self):
        self.online_avatars = None
        self.emails = None
        self.orders = None

    # 每日刷新
    def initRefreshTimer(self):
        offset = 0
        currTime = time.time()
        curTimeList = list(time.localtime())
        if curTimeList[4] != 0 or curTimeList[5] != 0:  # 分和秒不为0
            curTimeList[3] += 1  # 下个小时
            curTimeList[4] = 0
            curTimeList[5] = 0
            newTime = time.mktime(time.struct_time(curTimeList))
            offset = newTime - currTime

        offset += 1
        log.DEBUG_MSG('Lobby::initRefreshTimer offset: %f' % offset)
        self.addTimer(offset, 3600, TIMER_TYPE_REFRESH_DAILY_TASK)
        offset = 60 - currTime % 60
        self.addTimer(offset, 30, TIMER_TYPE_REFRESH_MINUTES)

    def avatarEnterWorld(self, entity, player_id):
        self.online_avatars[player_id] = entity
        # 处理未发送的订单
        # self.reqProduct(player_id)

    def avatarLeaveWorld(self, playerId):
        if playerId in self.online_avatars:
            del self.online_avatars[playerId]

    def onTimer(self, tid, userArg):
        if userArg == TIMER_TYPE_REFRESH_DAILY_TASK:
            self.createTodayRecord()
            self.createTodayAdsRecord()
            self.avatarDailyRefresh()
            ILobbySeasonRank.seasonMonthCheck(self)
        elif userArg == TIMER_TYPE_REFRESH_MINUTES:
            self.avatarMinuteRefresh()

    def avatarDailyRefresh(self):
        for player_id in self.online_avatars:
            self.online_avatars[player_id].dailyRefresh()

    def avatarMinuteRefresh(self):
        for player_id in self.online_avatars:
            self.online_avatars[player_id].minuteRefresh()

    def reqAccountId(self, account_entity_call):
        self.accountId += 1
        log.INFO_MSG(f'Lobby.reqAccountId accountId: {self.accountId}')
        account_entity_call.onReqAccountId(self.accountId)

    def reqPlayerId(self, account_entity_call):
        self.playerId += 1
        log.INFO_MSG(f'Lobby.reqPlayerId playerId: {self.playerId}')
        account_entity_call.onReqPlayerId(self.playerId)

    def updateNickName(self, playerId, groupId, nickName):
        self.tb_memeber.tb.updateLine({'nickName': nickName}, f'playerId={playerId}', None)
        if groupId in self.group_memebers:
            for player in self.group_memebers[groupId]['memebers']:
                if player['player_id'] == playerId:
                    player['nickName'] = nickName

    def updateHeadImgUrl(self, playerId, groupId, headImgUrl):
        self.tb_memeber.tb.updateLine({'headImgUrl': headImgUrl}, f'playerId={playerId}', None)
        if groupId in self.group_memebers:
            for player in self.group_memebers[groupId]['memebers']:
                if player['player_id'] == playerId:
                    player['headImgUrl'] = headImgUrl

    def setPlayerVip(self, playerId):
        log.INFO_MSG(f'setPlayerVip playerId: {playerId}')
        if playerId in self.online_avatars:
            self.online_avatars[playerId].setVip(1)
        else:
            def callback(result, rows, insertid, error):
                if error:
                    log.ERROR_MSG(f'setPlayerVip failed: {error}')
                else:
                    log.INFO_MSG(f'setPlayerVip success')
            sql = f'update tbl_Avatar set sm_vip = 1 where sm_playerId={playerId};'
            KBEngine.executeRawDatabaseCommand(sql, callback)

    def onRecharge(self, playerId, boc, prop_id):
        ILobbyPayment.addPaymentRecord(self, playerId, prop_id)
        if boc in self.serectKeyLst:
            log.DEBUG_MSG(f'repetitive serectKey: {boc}')
            if playerId in self.online_avatars:
                self.online_avatars[playerId].avatarOther.repRecharge(1, prop_id)
        else:
            self.serectKeyLst.append(boc)
            self.serectKeyLst = self.serectKeyLst
            log.DEBUG_MSG(f'add serectKey in Lst:{boc}')
            if playerId in self.online_avatars:
                self.online_avatars[playerId].avatarOther.repRecharge(0, prop_id)

    def addChallengeCount(self, userId):
        if userId not in self.todayChallengeLst:
            self.todayChallengeLst.append(userId)
            self.todayChallengeLst = self.todayChallengeLst

    def addCompleteCount(self, userId):
        if userId not in self.todayCompleteLst:
            self.todayCompleteLst.append(userId)
            self.todayCompleteLst = self.todayCompleteLst

    def updateLogIn(self, playerId):
        if playerId not in self.todayLoginPlayer:
            self.todayLoginPlayer.append(playerId)
            self.todayLoginPlayer = self.todayLoginPlayer
            self.updateTodayCount()

    def updateAds(self):
        self.updateTodayAdsCount()

    def record_invite_player(self, invite_id, playerId, playerName, playerChickenNumber):
        def callback(result, rows, insertid, error):
            if error:
                log.ERROR_MSG(f'record_invite_player failed: {error}')
            elif not result:
                self.changeLobbyInviteRecord(invite_id)
            else:
                log.DEBUG_MSG(f'record_invite_player success {len(result)}')
                parentId = int(result[0][0])
                point_sql = f'UPDATE tbl_Avatar_avatarOther SET sm_point = sm_point + 100, sm_coin = sm_coin + 500 WHERE parentID = {parentId}'
                info_Sql = f'insert into tbl_Avatar_avatarOther_invite_lst(parentID,sm_playerId,sm_playerName,sm_playerChickenNumber) values ({parentId}, {playerId}, \"{playerName}\", {playerChickenNumber})'
                KBEngine.executeRawDatabaseCommand(point_sql, None)
                KBEngine.executeRawDatabaseCommand(info_Sql, None)
                log.DEBUG_MSG(f'record invite player completed, invitor:{invite_id}, player:{playerId}')

        info = self.invite_player_info(playerId, playerName, playerChickenNumber)
        if invite_id in self.online_avatars:
            self.online_avatars[invite_id].avatarOther.addInviteInfo(info)
        else:
            # parentId = 0
            # 记录至数据库中
            sql = f'SELECT id from tbl_Avatar where sm_playerId = {invite_id}'
            #log.DEBUG_MSG(f'update friend record')
            KBEngine.executeRawDatabaseCommand(sql, callback)
            pass
        
    def invite_player_info(self, playerId, playerName, playerChickenNumber):
        info = {
            'playerId': playerId,
            'playerName': playerName,
            'playerChickenNumber': playerChickenNumber
        }
        return info

    def checkTransaction(self, account_entity_call, boc, prop_id):
        pass
        #result = asyncio.run(self.verifyTransactions(boc))
        # result = self.verifyTransactions(boc)
        # if result:
        #     if boc in self.serectKeyLst:
        #         log.DEBUG_MSG(f'repetitive serectKey: {boc}')
        #         account_entity_call.avatarOther.repRecharge(1, prop_id)
        #     else:
        #         self.serectKeyLst.append(boc)
        #         self.serectKeyLst = self.serectKeyLst
        #         log.DEBUG_MSG(f'add serectKey in Lst:{boc}')
        #         account_entity_call.avatarOther.repRecharge(0, prop_id)
        # else:
        #     log.DEBUG_MSG(f'transaction status is unfinish: {boc}')
        #     account_entity_call.avatarOther.repRecharge(2, prop_id)

    # def verifyTransactions(self, boc:str):
    #     # wallet_origin = "0:6ce2623692606e3796a5e04a93d49c4e1a1dcdb40f5737c8f6b502f10c59418e"0QCSES0TZYqcVkgoguhIb8iMEo4cvaEwmIrU5qbQgnN8fo2A
    #     try:
    #         # params = ParamsOfGetBocHash(boc=boc)
    #         # boc_info = self.tonclient.boc.get_boc_hash(params)
    #         # log.DEBUG_MSG(f"BOC Hash: {boc_info.hash}")
    #         parsed_boc = self.tonclient.boc.parse_message(ParamsOfParse(boc=boc))
    #         dst = parsed_boc.parsed['dst']
    #         log.INFO_MSG(f'解析成功，data:{parsed_boc.parsed}')
    #         if parsed_boc.parsed['status'] == 3 or parsed_boc.parsed['status'] == 5:
    #             return True
    #         else:
    #             return False
    #     except Exception as e:
    #         log.DEBUG_MSG(f'解析失败！！！{e}')
    #         return False
